/**
 * @description 动态加载initcommand 多进程处理
 */

"use strict";
const semver = require("semver"); //比对版本号
const colors = require("colors/safe");
const log = require("@spiritos-cli/log");
const { isObject } = require("@spiritos-cli/utils");
const LOWEST_NODE_VERSION = "12.0.0";

class Command {
  constructor(argv) {
    if (!argv) {
      throw new Error("参数不能为空！");
    }
    // if(!isObject(argv)){
    //   throw new Error('参数必须是对象')
    // }
    if (!Array.isArray(argv)) {
      throw new Error("参数必须是数组！");
    }

    if (argv.length < 1) {
      throw new Error("参数列表不能为空！");
    }

    // console.log(argv,"Command");
    this._argv = argv;
    let runner = new Promise((resolve, reject) => {
      let chain = Promise.resolve();
      chain = chain.then(() => this.checkNodeVersion());
      chain = chain.then(() => this.initArgs());
      chain = chain.then(() => this.init());
      chain = chain.then(() => this.exec());
      chain.catch((err) => {
        log.error(err.message);
      });
    });
  }

  /**
   * 参数初始化
   */
  initArgs() {
    this._cmd = this._argv[this._argv.length - 1];
    this._argv = this._argv.slice(0, this._argv.length - 1);
  }

  /**
   * 检查node版本号
   */
  checkNodeVersion() {
    //获取当前版本号
    const currentVersion = process.version;
    //第二步，比对最低版本号
    const lowestVersion = LOWEST_NODE_VERSION;
    if (!semver.gte(currentVersion, lowestVersion)) {
      throw new Error(
        colors.red(`spiritos-cli 需要安装v${lowestVersion}以上版本的 node.js`)
      );
    }
  }

  //命令的准备阶段
  init() {
    throw new Error("init必须实现");
  }

  // 命令的执行阶段
  exec() {
    throw new Error("exec必须实现");
    //console.log("Command consturctor");
  }
}

module.exports = Command;
